package com.lagou.edu.intercepter;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author 13771
 * @date 2020/8/9 22:56
 * @description
 */
public class CheckIntercepter implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取请求路径
        String requestURI = request.getRequestURI();
        if(requestURI.contains("login")){
            //如果是登录请求，直接放行
            return true;
        }
        //从session中获取登录信息
        Object username = request.getSession().getAttribute("username");
        if(username != null){
            //session中有登录信息，放行
            return true;
        }else{
            //session没有登录信息，跳转到登录页面
            response.sendRedirect("/index.jsp");
            return false;
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
